package com.rnd.kx.mvp.http.net;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * @author csd
 * @date 2019/3/28.
 * @description 拦截器工具类
 * */
public class IntercepterUtil {


    /**
     * 设置Header
     *
     * @return
     */
    public static Interceptor getHeaderInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(@NonNull Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder()
                        //添加Token
                        .header("token", "");
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        };

    }

    //日志拦截器
    public static HttpLoggingInterceptor logInterceptor(){
        return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.e("日志拦截器", "log: "+message);

            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印数据的级别
    }

    /**
     * token验证的拦截器
     * 当返回的code为400时，表示token过期，请求重置令牌，重置token
     * 当返回的code为401时，表示在别的地方登录了，或者这个token不存在了，就直接退出到登录页面
     * @return
     */
    public static Interceptor tokenInterceptor(){
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);
                //对返回code统一拦截
                if (response != null){
                    if (response.code() == 401){
                        //别处登录
                       }else if (response.code() == 400){
                        //刷新token
                    }
                }
                return response;
            }
        };
    }
}
